//
//  AddImageView.m
//  XinKaiFa55like
//
//  Created by 55like on 2017/9/26.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "AddImageView.h"
#import "LFImagePickerController.h"


@interface AddImageViewCell : UICollectionViewCell

@property (nonatomic,strong)UIImageView * imageview;

@property (nonatomic,strong)UIButton * cancelbtn;

@property (nonatomic,strong)NSIndexPath * indexpath;

@property (nonatomic,copy)void (^cleranblock)(NSInteger row);

@end

@implementation AddImageViewCell

-(UIImageView *)imageview{
    
    if (!_imageview) {
        
        UIImageView * imagvew = [[UIImageView alloc]init];
        imagvew.contentMode = UIViewContentModeScaleAspectFill;
        imagvew.clipsToBounds = YES;
        [self addSubview:imagvew];
        _imageview = imagvew;
        
    }
    
    return _imageview;
}
-(UIButton *)cancelbtn{
    
    if (!_cancelbtn) {
        
        UIButton * butt = [[UIButton alloc]init];
        [butt setImage:[UIImage imageNamed:@"xkf_imgclose"] forState:UIControlStateNormal];
        [butt addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:butt];
        _cancelbtn = butt;

    }
    
    
    return _cancelbtn;
}
-(void)cancle{
    
    [QAlertView showAlertViewWithTitle:@"是否删除此图片？" message:@"" cancelButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger index) {
       
        if (index == 1) {
            
            if (self.cleranblock) {
                self.cleranblock(self.indexpath.row);
            }
            
        }
        
    }];
    
}
@end

@interface AddImageView ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,LFImagePickerControllerDelegate>

@property (nonatomic,strong)UICollectionView * collectionView;



@end


@implementation AddImageView

static NSString * AddImageViewCellID = @"AddImageViewCellID";

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.maxNum = 9;
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.maxNum = 9;
    }
    return self;
}

-(void)reshData{
    
    
    [self.collectionView reloadData];
    
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        fl.minimumLineSpacing = 0;
        fl.minimumInteritemSpacing = 0;
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:fl];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.scrollEnabled = NO;
        collectionView.backgroundColor = [UIColor clearColor];
        [collectionView registerClass:[AddImageViewCell class] forCellWithReuseIdentifier:AddImageViewCellID];
        [self addSubview:collectionView];
        _collectionView = collectionView;
    }
    
    _collectionView.frame = CGRectMake(10, 0, self.frameWidth - 20, ((self.imageArray.count % 4 == 0?0:1) + self.imageArray.count / 4) * (self.frameWidth - 20)/4);
    self.frameHeight = _collectionView.frameHeight;
    return _collectionView;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    
    return 1;
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.imageArray.count;
    
}
//cell
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(collectionView.frameWidth/4, collectionView.frameWidth/4);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    EMWeakSelf(weakSelf);
    AddImageViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:AddImageViewCellID forIndexPath:indexPath];
    cell.indexpath = indexPath;
    cell.imageview.frame = CGRectMake(0, 10, cell.frameWidth - 10, cell.frameHeight - 10);
    cell.cancelbtn.frame = CGRectMake(cell.frameWidth - 18, 3, 15, 15);
    cell.cancelbtn.hidden = NO;
    id image = self.imageArray[indexPath.row];
    if ([image isKindOfClass:[UIImage class]]) {
        cell.imageview.image = image;
        
    }else if ([image isKindOfClass:[NSString class]]){
        
        [cell.imageview imageWithURL:image useProgress:NO useActivity:NO];
        
    }
    if (indexPath.row == self.imageArray.count - 1) {
        
        cell.cancelbtn.hidden = YES;
    }
    cell.cleranblock = ^(NSInteger row) {
    
        
        [weakSelf.imageArray removeObjectAtIndex:row];
        [weakSelf.collectionView reloadData];
        if (weakSelf.imageBlock) {
            weakSelf.imageBlock(weakSelf.imageArray,weakSelf.collectionView.frameHeight);
        }
        if (weakSelf.remBlock) {
            weakSelf.remBlock(row);
        }
        
    };
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",indexPath);
    
    EMWeakSelf(weakSelf);
    if (indexPath.row == self.imageArray.count - 1) {
        
        if (self.maxNum + 1 - self.imageArray.count <= 0) {
            
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"最多选择%ld张图片",(long)self.maxNum]];
            
            return;
        }
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [QAlertController showSheetQAlertControllerWithTitle:@"选择图片来源" message:@"" cancelBtn:@"取消" otherBtnArray:@[@"相机",@"相册"] showController:[self viewController] QAlertControllerClickBlock:^(int index) {
                if (index == 1) {
                    UIImagePickerController *imagepic = [[UIImagePickerController alloc]init];
                    imagepic.delegate = weakSelf;
                    imagepic.allowsEditing = YES;
                    imagepic.sourceType  = UIImagePickerControllerSourceTypeCamera;
                    [[weakSelf viewController] presentViewController:imagepic animated:YES completion:nil];
                }else if (index == 2){
 
                    LFImagePickerController *imagePicker = [[LFImagePickerController alloc] initWithMaxImagesCount:self.maxNum+1-self.imageArray.count delegate:weakSelf];
                    imagePicker.allowTakePicture = NO;
                    imagePicker.allowPickingVideo = NO;
                    imagePicker.doneBtnTitleStr = @"完成";
                    imagePicker.allowEditting = NO;
                    [[weakSelf viewController] presentViewController:imagePicker animated:YES completion:nil];

                }
            }];
        }else{
 
            [QAlertController showSheetQAlertControllerWithTitle:@"选择图片来源" message:@"" cancelBtn:@"取消" otherBtnArray:@[@"相册"] showController:[self viewController] QAlertControllerClickBlock:^(int index) {
       
                if (index == 1){
                    LFImagePickerController *imagePicker = [[LFImagePickerController alloc] initWithMaxImagesCount:self.maxNum+1-self.imageArray.count delegate:weakSelf];
                    imagePicker.allowTakePicture = NO;
                    imagePicker.allowPickingVideo = NO;
                    imagePicker.doneBtnTitleStr = @"完成";
                    imagePicker.allowEditting = NO;
                    [[weakSelf viewController] presentViewController:imagePicker animated:YES completion:nil];
                    
                }
                
            }];

        }
        
        
    }else{
        
        AddImageViewCell * cell = (AddImageViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        [Utility showBigImage:@[cell.imageview] clickIndex:0 viewContent:[self viewController] type:@"2"];

        
        
        
    }
    
}

#pragma mark LFImagePickerControllerDelegate
- (void)lf_imagePickerController:(LFImagePickerController *)picker didFinishPickingThumbnailImages:(NSArray<UIImage *> *)thumbnailImages originalImages:(NSArray<UIImage *> *)originalImages infos:(NSArray<NSDictionary *> *)infos
{
   
    
    for (NSInteger i = 0; i < originalImages.count; i++) {
        //        UIImage *thumbnailImage = thumbnailImages[i];
        UIImage *image = originalImages[i];
        //        NSDictionary *info = infos[i];
        //        NSString *name = [NSString stringWithFormat:@"%@.jpeg", info[kImageInfoFileName]];
        NSInteger count = self.imageArray.count;
        [self.imageArray insertObject:image atIndex:count-1];
    }
    [self.collectionView reloadData];
    if (self.imageBlock) {
        self.imageBlock(self.imageArray,self.collectionView.frameHeight);
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSInteger count = self.imageArray.count;
    [self.imageArray insertObject:image atIndex:count-1];
    [self.collectionView reloadData];
    
    if (self.imageBlock) {
        self.imageBlock(self.imageArray,self.collectionView.frameHeight);
    }
    [[self viewController] dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [[self viewController] dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}
-(NSMutableArray *)imageArray{
    
    if (!_imageArray) {
        
        _imageArray = [[NSMutableArray alloc]init];
        UIImage * image = [UIImage imageNamed:@"zdyadd"];
        [_imageArray addObject:image];
        
    }
    
    return _imageArray;
}

@end
